//
//  oldMomentDetalViewController.m
//  laonianbang
//
//  Created by 勇拓 李 on 18/4/2.
//  Copyright © 2018年 zaiyou. All rights reserved.
//

#import "oldMomentDetalViewController.h"
#import "MJRefresh.h"
#import "oldMomentsTableViewCell.h"
#import "oldMomentCommentTableViewCell.h"
#import "IQKeyboardManager.h"

@interface oldMomentDetalViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSInteger pageNo;
}
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIImageView *img_avatar;
@property (weak, nonatomic) IBOutlet UITextField *text_filed;
@property (weak, nonatomic) IBOutlet UITableView *table_view;
@property (weak, nonatomic) IBOutlet UIButton *btn_send;

@property (nonatomic, copy)oldComment *selectComment;

@property (nonatomic, copy)NSArray *commentArray;
@end

static NSString *const identifier = @"oldMomentsTableViewCell";
static NSString *const identifier_comment = @"oldMomentCommentTableViewCell";

@implementation oldMomentDetalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self initData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)keyboardWillHide:(NSNotification *)note{
    
    _selectComment = nil;
    _text_filed.placeholder = @"说点什么..";
}
#pragma mark - initView
- (void)initView
{
    self.navigationItem.title = @"活动详情";
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [self initTableView];
    _img_avatar.layer.cornerRadius = 35/2;
    [_img_avatar showHeadImg:ACCOUNT_SINGLETON.accountInfo.avatar];
    _btn_send.layer.cornerRadius = 6.f;
    [_btn_send addTarget:self action:@selector(btn_send_tapped:) forControlEvents:UIControlEventTouchDown];
}

- (void)initTableView
{
    [self.table_view registerNib:[UINib nibWithNibName:identifier bundle:nil] forCellReuseIdentifier:identifier];
    [self.table_view registerNib:[UINib nibWithNibName:identifier_comment bundle:nil] forCellReuseIdentifier:identifier_comment];
    
    self.table_view.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];//隐藏空的 cell
    self.table_view.delegate = self;
    self.table_view.dataSource = self;
    
    self.table_view.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.table_view.estimatedRowHeight = 213;
    self.table_view.rowHeight = UITableViewAutomaticDimension;
}


#pragma mark - initData
- (void)initData
{
    self.table_view.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.table_view.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    
    if(!_moment)
    {
        [self initMomentData];
    }
    else
    {
        [self.table_view.mj_header beginRefreshing];
    }
}

- (void)initMomentData
{
    [oldHub waiting:@"加载中"];
    
    WeakSelf
    
    [OLDNetWork httpRequestWithPostPut:URL_GetDetailByFid params:@{@"fid":_fid} success:^(id data) {
        [oldHub hideHUD];
        if (data) {
            weakSelf.moment = [[oldMoment alloc] initWithDictionary:data];
            [weakSelf.table_view.mj_header beginRefreshing];
        }
    } error:^(NSString *error) {
        [oldHub warningUser:error];
    }];
}

- (void)refresh
{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:_moment.fid, @"fid", @"1", @"pageNum", @"10", @"pageSize", nil];
    
    [self loadData:params ifResetPageNo:YES];
}

- (void)loadMore
{
    NSString *pageNum = [NSString stringWithFormat:@"%ld", (long)pageNo + 1];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: _moment.fid, @"fid",pageNum, @"pageNum", @"10", @"pageSize", nil];
    
    [self loadData:params ifResetPageNo:NO];
}

- (void)loadData:(NSDictionary *)params ifResetPageNo:(BOOL)reset
{
    WeakSelf
    
    [OLDNetWork httpRequestWithPostPut:URL_GetCommentByFid params:params success:^(id data) {
        if (reset) {
            pageNo = 1;
            weakSelf.commentArray = [NSArray array];
            [weakSelf.table_view.mj_header endRefreshing];
        }
        else
        {
            pageNo ++;
            [weakSelf.table_view.mj_footer endRefreshing];
        }
        
        [weakSelf initDataSource:data];
        [weakSelf.table_view reloadData];
        
    } error:^(NSString *error) {
        if (reset) {
            [weakSelf.table_view.mj_header endRefreshing];
        }
        else
        {
            [weakSelf.table_view.mj_footer endRefreshing];
        }
        [oldHub warningUser:error];
    }];
}

- (void)initDataSource:(id)data
{
    NSMutableArray *array = [_commentArray mutableCopy];
    
    for (int i = 0; i < [data count]; i++) {
        oldComment *moment = [[oldComment alloc] initWithDictionary:data[i]];
        [array addObject:moment];
    }
    
    _commentArray = array;
}

#pragma mark - send
- (void)btn_send_tapped:(id)sender
{
    WeakSelf
    
    NSCharacterSet  *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *text = [_text_filed.text stringByTrimmingCharactersInSet:set];
    
    if (![text length]) {
        [oldHub warningUser:@"评论不能为空"];
        return;
    }
    
    [oldHub waiting:@"发送中.."];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: _moment.fid, @"fid", text, @"content", nil];
    
    if(_selectComment)
    {
        [params setObject:_selectComment.replyUserInfo.uid forKey:@"mentionedUid"];
    }
    
    [_text_filed resignFirstResponder];
    
    [OLDNetWork httpRequestWithPostPut:URL_AddComment params:params success:^(id data) {
        weakSelf.text_filed.text = nil;
        [oldHub hideHUD];
        NSInteger number = [weakSelf.moment.commentCount integerValue];
        weakSelf.moment.commentCount = [NSString stringWithFormat:@"%ld", number + 1];
        [weakSelf.table_view.mj_header beginRefreshing];
    } error:^(NSString *error) {
        [oldHub warningUser:error];
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            if (_moment) {
                return 1;
            }
            else
            {
                return 0;
            }
            break;
        default:
            return [_commentArray count];
            break;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
            return [self configTopCell:tableView cellForRowAtIndexPath:indexPath];
            break;
        default:
            return [self configCommentCell:tableView cellForRowAtIndexPath:indexPath];
            break;
    }
}


- (UITableViewCell *)configTopCell:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    oldMomentsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[oldMomentsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.moment = _moment;
    
    return cell;
}

- (UITableViewCell *)configCommentCell:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    oldMomentCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier_comment forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[oldMomentCommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier_comment];
    }
    
    cell.comment = _commentArray[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 1)
    {
        _selectComment = _commentArray[indexPath.row];;
        _text_filed.placeholder = [NSString stringWithFormat:@"回复%@",_selectComment.replyUserInfo.uname];
        [self.text_filed becomeFirstResponder];
    }
}

@end
